package com.hema.auction.http.biz;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hema.auction.R;
import com.hema.auction.bean.SysUnits;
import com.hema.auction.http.HttpTag;
import com.hema.auction.listener.RequestCallBack;
import com.hema.auction.utils.UpdateUtil;
import com.hema.auction.utils.Utils;
import com.hema.auction.utils.manager.SPManager;
import com.hema.auction.widget.dialog.LoadingDialog;

import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

/**
 * auther by john
 * 版本更新工具类
 */
public class UpdateManager implements RequestCallBack {

    private static UpdateManager instance;
    private LoadingDialog loadingDialog;
    private Call call;
    private AppCompatActivity activity;
    private String versionName;
    private String url;
    private boolean isForce, showDialog;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(Message msg) {
            if (showDialog)
                if (!activity.isFinishing())
                    if (loadingDialog != null)
                        loadingDialog.dismiss();
            switch (msg.what) {
                case 0://有新版本
                    updateDialog();
                    break;
                case 1://无新版本
                    if (showDialog)
                        Utils.showToast(activity, R.string.no_new_version);
                    break;
                case 2://请求失败
                    if (showDialog)
                        Utils.showToast(activity, R.string.request_error);
                    break;
            }
        }
    };


    public static UpdateManager getInstance() {
        if (instance == null) {
            instance = new UpdateManager();
        }
        return instance;
    }

    /**
     * 检查更新
     *
     * @param activity
     */
    public void checkUpdate(AppCompatActivity activity, boolean showDialog) {
        this.activity = activity;
        this.showDialog = showDialog;
        call = HttpManager.getInstance(activity).getSysUnits(this);
        if (showDialog) {
            if (loadingDialog == null) {
                loadingDialog = new LoadingDialog();
            }
            loadingDialog.show(activity.getSupportFragmentManager());

            activity.getSupportFragmentManager().executePendingTransactions();
            Dialog dialog = loadingDialog.getDialog();
//        if (dialog != null) {
//            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
//                @Override
//                public void onCancel(DialogInterface dialog) {
//
//                }
//            });
//        }
        }
    }

    @Override
    public void onFailure(HttpTag eventCode, Call call, IOException e) {
        handler.sendEmptyMessage(2);
    }

    @Override
    public void onResponse(HttpTag eventCode, Call call, Response response) {
        if (response.isSuccessful()) {
            try {
                JSONObject result = new JSONObject(response.body().string());
                if (result.getInt("errcode") == 0) {
                    List<SysUnits> sysUnitses = new Gson().fromJson(result.getJSONArray("data").toString(), new TypeToken<List<SysUnits>>() {
                    }.getType());
                    if (sysUnitses != null) {
                        int httpVersionCode = 0;
                        for (SysUnits sysUnits : sysUnitses) {
                            if (sysUnits.getTab().equals("android_version")) {
                                httpVersionCode = Integer.valueOf(sysUnits.getValue());
                                SPManager.getInstance(activity).setHttpVersionCode(httpVersionCode);

                                continue;
                            }
                            if (sysUnits.getTab().equals("apk_url")) {
                                url = sysUnits.getValue();
                                SPManager.getInstance(activity).setHttpApkUrl(url);
                                continue;
                            }
                        }
                        if (httpVersionCode > Utils.getVersionCode(activity)) {
                            handler.sendEmptyMessage(0);
                        } else {
                            handler.sendEmptyMessage(1);
                        }
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
                handler.sendEmptyMessage(2);
            }
        }
    }

    @Override
    public void onRequestFinish(HttpTag eventCode) {

    }

    private void updateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity, R.style.MyDialog);
        builder.setMessage(activity.getString(R.string.has_new_version));
        builder.setPositiveButton("更新", (dialog, which) -> {
            Utils.showToast(activity, "正在下载...");
            new UpdateUtil(activity.getApplicationContext(), versionName, url).start();
        });
        if (!isForce) {
            builder.setNegativeButton("取消", (dialog, which) -> {

            });
        } else {
            builder.setCancelable(false);
        }
        builder.create().show();
    }
}
